package com.trw.trp.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.trw.trp.database.ConnectionPool;
import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class AbstractDao {
	private static Log log = LogFactory.getLog(AbstractDao.class);
	private static int retryCount = 10;

	protected Connection getConnection() throws SQLException {
		Connection conn = ConnectionPool.getConnection();
		if (conn == null) {
			log.warn("can't get db connection, will retry " + retryCount
					+ " times.");
			for (int i = 0; i < retryCount; i++) {
				log.info("retry" + (i + 1) + "times");
				conn = ConnectionPool.getConnection();
				if (conn != null) {
					log.info("get db connection after " + (i + 1) + " retries");
					break;
				}
			}
			if (conn == null) {
				log.warn("still can't get db connection after retry "
						+ retryCount + " times.");
			}
		}
		return conn;
	}

	protected void close(Connection conn, ResultSet rs, Statement... statements) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				log.warn(e);
			}
		}
		if (statements != null && statements.length > 0) {
			for (Statement statement : statements) {
				try {
					if (statement != null) {
						statement.close();
					}
				} catch (SQLException e) {
					log.warn(e);
				}
			}
		}
		if (conn != null) {
			ConnectionPool.releaseConnection(conn);
		}
	}

}
